﻿using HlELock.Core;
using Prism.Commands;
using Prism.Mvvm;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Documents;

namespace HlElock.Tool.ViewModels
{
    internal class MainWindowViewModel : BindableBase
    {
        public MainWindowViewModel()
        {
            RefreshUseHid();
        }
        private IUsbHid _usbHid;
        public IUsbHid UsbHid
        {
            get { return _usbHid; }
            set { SetProperty(ref _usbHid, value); }
        }

        private List<IUsbHid> UsbList { get; set; }

        public void RefreshUseHid()
        {
            var usbList = UsbHidHelper.GetDeviceList();
            if (UsbList != null)
            {
                if (UsbList.Count > usbList.Count)
                {
                    UsbHid = null;
                }
                else if (UsbList.Count < usbList.Count)
                {
                    var lst = usbList.Except(UsbList, new UsbHidComparer());
                    UsbHid = lst.First();
                }
            }
            UsbList = usbList;
        }

        private DelegateCommand _rewriteCommand;
        public DelegateCommand RewriteCommand =>
            _rewriteCommand ?? (_rewriteCommand = new DelegateCommand(ExecuteRewriteCommand));

        void ExecuteRewriteCommand()
        {

            UsbHid.OpenWithPath();
            UsbHid.SendMessage("584B504B0201");
            UsbHid.SendMessage("584B504B0202");
            UsbHid.SendMessage("584B504B0204");
            if (UsbHid.RewriteInfo())
            {
                MessageBox.Show("重写硬件成功");
            }
            else
            {

            }

        }
    }

    class UsbHidComparer : IEqualityComparer<IUsbHid>
    {
        public bool Equals(IUsbHid x, IUsbHid y)
        {
            if (x == null || y == null) return false;
            return x == y || (x.PID == y.PID && x.VID == y.VID);

        }

        public int GetHashCode(IUsbHid obj)
        {
            return (obj.PID.ToString() + obj.VID.ToString()).GetHashCode();
        }
    }
}
